package org.kimoji.search;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Singleton;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Searcher {
	private static Logger logger = Logger.getLogger(Searcher.class);
	
	private IndexSearcher indexSearcher;
	@Autowired
	private SimpleFSDirectory luceneDirectory;
	@Autowired
	private  StandardAnalyzer analyzer;
	
	private IndexReader reader;
	
	private static SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>");
	
	@PostConstruct
	public void init(){
		try {
			reader = IndexReader.open(luceneDirectory);
			indexSearcher = new IndexSearcher(reader);
		} catch (CorruptIndexException e) {
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
	
	public SearchData search(SearchData data) {
		int pageSize = data.getPageSize();
		int pageNum = data.getPageNum()+1;
		int start = (pageNum-1)*pageSize;
		
		String lql = makeLql(data);
//		System.out.println("begin:"+Calendar.getInstance().getTimeInMillis());
//		System.out.println("----------------------------------------------------------------------------------------------------");
		System.out.println(lql);
//		System.out.println("----------------------------------------------------------------------------------------------------");
		QueryParser queryParser = new QueryParser(Version.LUCENE_36, "", analyzer);
		queryParser.setAllowLeadingWildcard(true);
		queryParser.setEnablePositionIncrements(false);
		queryParser.setLowercaseExpandedTerms(false);
		queryParser.setDefaultOperator(QueryParser.OR_OPERATOR);
		try {
			if(null == reader)
				reader = IndexReader.open(luceneDirectory);
			IndexReader nr = IndexReader.openIfChanged(reader);
			if (nr != null){
				reader = nr;
				indexSearcher = new IndexSearcher(reader);
			}
			if(null == indexSearcher){
				indexSearcher = new IndexSearcher(reader);
			}
			Query query = queryParser.parse(lql);
			/* ------结果排序------ */
//			String orderType = data.getCondition().getOrder_by_type();
//			String orderField = data.getCondition().getOrder_by_field();
			Sort sort = new Sort();
//			if(P.equals(orderField)){
//				if(A.equals(orderType)){
//					sort.setSort(new SortField("PRICE", SortField.FLOAT,false));
//				}else if(D.equals(orderType)){
//					sort.setSort(new SortField("PRICE", SortField.FLOAT,true));
//				}
//			}else{
////				sort.setSort(new SortField("GOODS_SORT", SortField.INT,false));
//			}
			
			Highlighter highlighter = new Highlighter(simpleHtmlFormatter, new QueryScorer(query,"GOODS_NAME"));
			data.setAnalyzer(analyzer);
			data.setHighlighter(highlighter);
			
			
			TopDocs topDocs = indexSearcher.search(query , pageSize * pageNum , null == sort ? new Sort() : sort);
			data.setTotal(topDocs.totalHits);
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
			List<Document> documents = new ArrayList<Document>();
			int end = start+pageSize>scoreDocs.length?scoreDocs.length:start+pageSize;
			for(int i=start;i<end;i++){
				Document document = indexSearcher.doc(scoreDocs[i].doc);
				documents.add(document);
			}
			data.setDocuments(documents);
			System.out.println("end:"+Calendar.getInstance().getTimeInMillis());
		} catch (Exception e) {
			
		}finally{
			
		}
		return data;
	}
	
	private String makeLql(SearchData data) {
		String keyword = data.getKeyword();
		StringBuffer lql = new StringBuffer("IS_DEL:n");
//		String lql = "IS_DEL:n ";
		/* -----拼接关键词----- */
		
		if(null != keyword && !"".equals(keyword.trim())){
//			List<String> kws = CommonAnalyzer.parse(keyword);//分词处理
//			kws.add(keyword);
			List<String> lqls = new ArrayList<String>();
//			for(String kw : kws){
//				lqls.add(" CONTENT:\""+kw+"\"");
				if(!keyword.matches("\\d*")){
					lqls.add(" GOODS_NAME:"+keyword+"^40");	
//					lqls.add(" ELEMENT:\""+kw+"\"^2");	
//					lqls.add(" CLASS_NAME:\""+kw+"\"^1");	
				}
//			}
			lql.append(" AND ( ").append(StringUtils.join(lqls," or ")).append(" ) ");
		}
		/* -----拼接关键词 end----- */
		
		return lql.toString();
	}
	
}
